package com.winner;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 原文链接：https://blog.csdn.net/guaoran/article/details/108304582
 * ReentrantLock 可重入锁  同一把锁
 *
 * @Author guaoran
 * @Description ReentrantLock 加锁、await、signal
 * 2019-05-22 13:36
 */
public class ReentrantLockDemo {

    public static void main(String[] args) {
        // 实例化一把重入锁  Lock lock = new ReentrantLock(true);
        Lock lock = new ReentrantLock();
        // 获得 condition
        Condition condition = lock.newCondition();
        // 启动两个线程，维护同一把锁和condition
        new LockAwaitDemo(lock,condition).start();
        new LockSignalDemo(lock,condition).start();
    }

    static class LockAwaitDemo extends Thread {
        private Lock lock;
        private Condition condition;

        public LockAwaitDemo(Lock lock, Condition condition) {
            this.lock = lock;
            this.condition = condition;
        }

        @Override
        public void run() {
            lock.lock();
            try {
                System.out.println("await...start");
                condition.await();
                System.out.println("await...end");
            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
                lock.unlock();
            }
        }
    }

    static class LockSignalDemo extends Thread {
        private Lock lock;
        private Condition condition;

        public LockSignalDemo(Lock lock, Condition condition) {
            this.lock = lock;
            this.condition = condition;
        }

        @Override
        public void run() {
            lock.lock();
            try {
                System.out.println("signal...start");
                condition.signal();
                System.out.println("signal...end");
            } finally {
                lock.unlock();
            }
        }
    }
}

